import time
import  random

random_macs = [0 for x in range(0, 80)]#random.sample(range(0, 0xFFFFFFFFFFFF), 80)
macs_ip = [0 for x in range(0, 80)]
ip = 0

def vdata_find_mac(brecv_ytes):
    dev_num = 0
    count = 0
    mac_index = 0
    global random_macs
    global macs_ip
    global ip
    for mac in random_macs:
        count = count + 1
        mask = ((1 << (4 * (brecv_ytes[0] + 1))) - 1)
        mac_half = mac & mask
        recv_mac = (brecv_ytes[1] << 0) + (brecv_ytes[2] << 8) + (brecv_ytes[3] << 16) + (brecv_ytes[4] << 24) + (
                brecv_ytes[5] << 32) + (brecv_ytes[6] << 40)
        recv_half = recv_mac & mask
        if macs_ip[count - 1] != 0:
            #print("跳过，已记录该Mac[%012X]]->[%d]" % (random_macs[mac_index - 1], ip))
            continue
        if mac_half == recv_half:
            mac_index = count
            dev_num = dev_num + 1
        if count == 80:
            if dev_num == 0:
                #print("没有Mac符合...")
                return 0
            elif dev_num == 1:
                #print("只有一个Mac符合...[%012X]" % random_macs[mac_index - 1])
                macs_ip[mac_index - 1] = ip
                ip += 1
                return 1
            else:
                #print("有%d个Mac符合..." % dev_num)
                return 2

send_count = 0

def request_mac_logic(init_addr, half_index):
    global send_count
    index = half_index
    for i in range(index,12):
        #print("查找%d区域..." %i)
        for j in range(0, 16):
            find_mac = init_addr + (j << (index * 4))
            #print("查找匹配Mac %X结尾..." %find_mac)
            comand = [i, (find_mac & 0xFF), ((find_mac >> 8) & 0xFF), ((find_mac >> 16) & 0xFF), ((find_mac >> 24) & 0xFF), ((find_mac >> 32) & 0xFF), ((find_mac >> 40) & 0xFF)]
            res = vdata_find_mac(comand)
            send_count += 1
            print("发送查询帧 %d次..." % send_count)
            if res == 2:
                request_mac_logic(find_mac, i + 1)

if __name__== '__main__':
    for i in range(40):
        random_macs[i*2] = 0xFFFFFFFFFFFF - i
        random_macs[i*2 + 1] = 0xEFFFFFFFFFFF - i
    request_mac_logic(0 , 0)
    print("over...")
